package cn.com.chec.en.controller.scheduler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import cn.com.chec.en.dao.DBInfoDao;
import cn.com.chec.en.util.FileUtils;

public class SchedulerListenr extends HttpServlet {
	private static final long serialVersionUID = -4771436350331390620L;
	protected static final Logger logger = Logger
			.getLogger(SchedulerListenr.class);

	public void init(ServletConfig config) throws ServletException {
		String cronExpression = "";
		try {
			String configPath = config.getServletContext().getRealPath("/")
					+ "WEB-INF/pages/admin/sysProperties/schdulerDB";
			InputStream is = new FileInputStream(new File(configPath));

			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = br.readLine()) != null) {
				if (StringUtils.isNotBlank(line)) {
					cronExpression = cronExpression + line;
				}
			}
			br.close();
			is.close();
			logger.info("[SchedulerListenr] cronExpression [" + cronExpression
					+ "]");

			DBInfoDao dao = new DBInfoDao();
			List<String> tblNameList = dao.getAllTables();
			String tblNames = "";
			for (String tblName : tblNameList) {
				tblNames = tblNames + " " + tblName;
			}

			String mysqlDumpDir = config.getServletContext().getRealPath("/")
					+ "/WEB-INF/pages/admin/sysProperties/sqlDump/";
			FileUtils.mkdirs(mysqlDumpDir);

			logger.info("[SchedulerListenr] cronExpression [" + cronExpression
					+ "] destFileDir [" + mysqlDumpDir + "]");

			DumpMysqlDataScheduler sched = new DumpMysqlDataScheduler();

			sched.removeJob();

			sched.startJob(cronExpression, tblNames, mysqlDumpDir);
		} catch (IOException e) {
			logger.info("[SchedulerListenr] error ", e);
		}
	}

	public void destroy() {
		super.destroy();
	}
}